package com.fowo.api.syncAmazon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.entity.AmazonRemovalOrder;
import com.fowo.api.entity.TmpRemovalOrder;
import com.fowo.api.mapper.AmazonRemovalOrderMapper;
import com.fowo.api.mapper.TmpRemovalOrderMapper;
import com.fowo.api.syncAmazon.api.RemovalOrderReportService;
import com.fowo.api.syncAmazon.mapper.AmazonTmpMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class RemoveOrderServiceImpl extends ServiceImpl<AmazonRemovalOrderMapper, AmazonRemovalOrder> {

    @Resource
    private TmpRemovalOrderMapper tmpRemovalOrderMapper;
    @Resource
    private RemovalOrderReportService reportService;
    @Resource
    private AmazonTmpMapper amazonTmpMapper;

    /**
     * 同步移除订单
     *
     * @throws Exception
     */
    public void syncRemoveOrder() throws Exception {
        //清空临时表
        amazonTmpMapper.deleteAllRemovalOrder();
        //拉取数据到临时表
        reportService.getRemovalOrder();
        //获取临时表数据
        List<TmpRemovalOrder> removalOrders = tmpRemovalOrderMapper.selectList(new QueryWrapper<TmpRemovalOrder>().eq("del_flag", 0));
        List<AmazonRemovalOrder> insertList = new ArrayList<>();
        if (removalOrders != null && removalOrders.size() > 0) {
            for (TmpRemovalOrder removalOrder : removalOrders) {
                QueryWrapper<AmazonRemovalOrder> orderWrapper = new QueryWrapper<>();
                orderWrapper.eq("del_flag",0);
                orderWrapper.eq("sid",removalOrder.getSid());
                orderWrapper.eq("order_id",removalOrder.getOrderId());
                int count = (int)this.count(orderWrapper);
                if(count > 0){
                    continue;
                }
                AmazonRemovalOrder amazonRemovalOrder = new AmazonRemovalOrder();
                BeanUtils.copyProperties(removalOrder, amazonRemovalOrder);
                amazonRemovalOrder.setId(null);
                amazonRemovalOrder.setCreateTime(new Date());
                insertList.add(amazonRemovalOrder);
            }
            List<List<AmazonRemovalOrder>> partition = Lists.partition(insertList, 200);
            for (List<AmazonRemovalOrder> amazonRemovalOrders : partition) {
                this.saveBatch(amazonRemovalOrders);
            }
        }
    }

}
